﻿using System;
using System.Diagnostics;
using System.IO;

namespace NetstsadmService
{
    public class Services : ICommandExecuter
    {
        public string ExecuteCommand(string input)
        {
            Logger logger = Logger.GetLogger();
            logger.Notify(input);

            ProcessStartInfo startInfo;
            if (input.IndexOf(' ') > -1)
            {
                string command = input.Substring(0, input.IndexOf(' '));
                startInfo = new ProcessStartInfo(command);
                startInfo.Arguments = input.Substring(input.IndexOf(' ') + 1);
            }
            else
            {
                startInfo = new ProcessStartInfo(input);
            }

            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.CreateNoWindow = true;
            Process process = Process.Start(startInfo);

            string errorString = "";
            process.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e)
            {
                if (!string.IsNullOrEmpty(e.Data))
                {
                    errorString += e.Data + "\n";
                }
            };

            process.BeginErrorReadLine();

            string output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();

            if (!string.IsNullOrEmpty(errorString))
            {
                return errorString;
            }
            else
            {
                return output;
            }
        }

        public string UploadFile(byte[] f, string fileName)
        {
            Logger logger = Logger.GetLogger();
            try
            {
                MemoryStream ms = new MemoryStream(f);
                FileStream fs = new FileStream(Path.Combine(Path.GetTempPath(), fileName), FileMode.Create);
                ms.WriteTo(fs);
                ms.Close();
                fs.Close();
                fs.Dispose();
                string path = Path.Combine(Path.GetTempPath(), fileName);
                logger.Notify(string.Format(Resource.FILE_UPLOADED, fileName, path));
                return path;
            }
            catch (Exception)
            {
                logger.Notify(Resource.ERROR_FILE_UPLOAD);
                return "";
            }
        }
    }
}
